package com.example.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.consts.CommonConstant;
import com.example.demo.dto.MenuPageParam;
import com.example.demo.dto.MenuParam;
import com.example.demo.entity.Menu;
import com.example.demo.enums.MenuAppCodeEnum;
import com.example.demo.mapper.MenuMapper;
import com.example.demo.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.tree.TreeTool;
import com.example.demo.vo.MenuVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 系统管理-菜单权限表 服务实现类
 * </p>
 *
 * @author vicente
 * @since 2024-01-24
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(MenuParam param) {
        param.setId(null);
        Menu menu = new Menu();
        BeanUtil.copyProperties(param, menu);
        return super.save(menu);
    }

    @Override
    public boolean update(MenuParam param) {
        Menu menu = new Menu();
        BeanUtil.copyProperties(param, menu);
        return super.updateById(menu);
    }

    @Override
    public List<Dict> appList() {
        List<Dict> dictList = new ArrayList<>();
        Arrays.stream(MenuAppCodeEnum.values()).forEach(item->{
            Dict dict = new Dict();
            dict.put(CommonConstant.VALUE, item.toString().toLowerCase());
            dict.put(CommonConstant.LABEL, item.getMessage());
            dictList.add(dict);
        });
        return dictList;
    }

    @Override
    public List<MenuVO> tree(MenuPageParam param) {
        QueryWrapper queryWrapper = param.buildQueryWrapper();
        queryWrapper.orderByAsc("sort");
        List<Menu> list = this.list(queryWrapper);
        List<MenuVO> menuVOS = BeanUtil.copyToList(list, MenuVO.class);
        List<MenuVO> treeData = TreeTool.listToTree(menuVOS,0L,MenuVO.class);
        //List<MenuVO> treeData = TreeTool.listToTree(BeanUtil.copyToList(list,MenuVO.class),0L,MenuVO.class);
        return treeData;
    }

}
